

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:s_mankey/config/net/api.dart';
import 'package:s_mankey/config/net/smonkey_ui_api.dart';
import 'package:s_mankey/config/resource_mananger.dart';
import 'package:s_mankey/config/router_config.dart';
import 'package:s_mankey/config/storage_manager.dart';
import 'package:s_mankey/service/smonkey_repository.dart';
import 'package:s_mankey/ui/widget/error_widget.dart';
import 'package:s_mankey/ui/widget/loading_widget.dart';
import 'package:s_mankey/ui/widget/search_bar.dart';
import 'package:s_mankey/view_model/my_page_vmodel.dart';

class ChooseSource1 extends StatefulWidget {

  final arguments;

  ChooseSource1({this.arguments});

  @override
  _ChooseSource1 createState() => _ChooseSource1();

}

class _ChooseSource1 extends State<ChooseSource1>{

  TextEditingController controller;
  Map<String, dynamic> searchOptions = Map(); //  搜索请求参数
  Map<String, dynamic> inviteOptions = Map(); //  邀请请求参数
  bool showResult = false;

  @override
  void initState() {
    controller = TextEditingController();
    setState(() {
      showResult = false;
    });
//    Provider.of<CourseInvitation>(context,listen: true).onResult(false); //实始化搜索结果
    super.initState();
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }


  @override
  Widget build(BuildContext context) {
    var _model = Provider.of<CourseInvitation>(context,listen: true);

    if(widget.arguments['city'] != null){
      searchOptions['city'] = widget.arguments['city'];
      inviteOptions['city'] = widget.arguments['city'];
    }

    searchOptions['mobile'] = controller.text;


    return Scaffold(
      resizeToAvoidBottomPadding: false,
      appBar: AppBar(
        backgroundColor: Colors.white,
        actions: [
          GestureDetector(onTap: (){
//            city: GZ
//            course_type: D40
//            member_id: 1572

            Navigator.pushNamed(context, RouterName.inviteRecord);

          },child: Container(
              padding: EdgeInsets.only(right: 10),
              alignment: Alignment(0, 0),
              child: Text('邀请记录')),),
        ],
        elevation: 0,
        title: Text('选择课程'),
      ),
      body:
      ListView(
        shrinkWrap: true,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.only(top: 15),
            child: SearchBar(controller: controller,callBack: (){
              setState(() {
                showResult = true;
              });

//              _model.onResult(true);
//              print('现在的++ ${_model.showResult}');
            },),
          ),

    !showResult? Text('') :
    FutureBuilder(future: SmonkeysRepository.fetchMySearchChooseCourse(options: searchOptions),builder:
    (BuildContext context, AsyncSnapshot snapshot) {

    /// 请求中
    if (snapshot.connectionState != ConnectionState.done) {
    return LoadingWidget();
    }
    /// 请求结束, 错误
    if (snapshot.hasError) {
    // 请求失败，显示错误
      DioError error = snapshot.error;
    return datasErrorWidget(errorTip: error.error.toString());
    }

    /// 请求成功，显示数据
    return SeachCourseResults(datas: snapshot.data,
      detailCallBack: (){
            Navigator.pushNamed(context, RouterName.courseDetail);
          },
      //确认邀请详情
            confirmCallBack: (){
      print('####${_model.cellData}');
              if(_model.cellData != null){
                inviteOptions['course_type'] = _model.cellData['course_type'];
                inviteOptions['member_id'] = _model.cellData['member_id'];
              }
              Navigator.pushNamed(context, RouterName.confirmINvite,arguments: inviteOptions);
            },
          );}),
        ],),
    );
  }

}

/// 搜索课程列表
class SeachCourseResults extends StatefulWidget {

  Function confirmCallBack; ///确认课程
  Function detailCallBack; ///课程详情
  final datas;

  SeachCourseResults({this.detailCallBack,this.confirmCallBack,this.datas});

  @override
  _SeachCourseResultsState createState() {
    return _SeachCourseResultsState();
  }
}

class _SeachCourseResultsState extends State<SeachCourseResults> {
  ScrollController _controller;

  @override
  void initState() {
    _controller = ScrollController();
    super.initState();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return
      Column(
      children: [
        Padding(
          padding: const EdgeInsets.fromLTRB(0, 10, 0, 10),
          child: Text(
            widget.datas['member_name'].toString(),
            style: TextStyle(fontSize: AppFontSize.Size16),
          ),
        ),

        ///TODO: 这里需要写固定高度, 才不会报错, 没有办法计算动态高度.. 看看后面如何解决
        Container(
          height: 700,
          child: Card(
            child: ListView.builder(
                controller: _controller,
                itemCount: widget.datas['list'].length,
                itemBuilder: (BuildContext context, int index) {
                  List list = []; //对象转换成数据
                  widget.datas['list'].forEach((key, value) {
                    list.add(widget.datas['list'][key]);
                  });

                  /// 保存 confimDetail请求参数
                  Map<String, dynamic> options = list[index];
                  options['member_id'] = widget.datas['member_id'];

                  Provider.of<CourseInvitation>(context,listen: false).tapCellData(options); //全局保存cell数据

                  return
                    GestureDetector(onTap: widget.detailCallBack, child:
                    Container(
                      margin: EdgeInsets.fromLTRB(15, 0, 0, 0),
                      padding: EdgeInsets.fromLTRB(0, 15, 0, 15),
                      decoration: BoxDecoration(
                          border: Border(
                              bottom: BorderSide(color: AppColor.dividerColor))),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Padding(
                            padding: const EdgeInsets.only(right: 8),
                            child: Image.network(
                              list[index]['type_photo_link'],
                              width: 82,
                              height: 117,
                              fit: BoxFit.fill,
                            ),
                          ),
                          Expanded(
                            child: Padding(
                              padding: const EdgeInsets.only(left: 3),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  //标题
                                  Row(
                                    mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                    children: [
                                      Row(
                                        children: [
                                          Text(list[index]['course_name']),
                                          IconFonts.rightIcon,
                                        ],
                                      ),
                                      GestureDetector(onTap: widget.confirmCallBack,
                                      child: Padding(
                                        padding: const EdgeInsets.only(right: 8),
                                        child: Icon(
                                          Icons.check,
                                          size: 18,
                                        ),
                                      ),),
                                    ],
                                  ),

                                  //内容
                                  Container(
                                    padding: EdgeInsets.fromLTRB(0, 5, 0, 5),
                                    child: Text(
                                      list[index]['type_short_desc'],
                                      style: TextStyle(
                                          color: Color(0xff747474),
                                          fontSize: AppFontSize.Size14),
                                      softWrap: true,
                                      maxLines: 3,
                                    ),
                                  ),

                                  Row(
                                    children: [
                                      Text(
                                        '上课时间：',
                                        style: TextStyle(
                                            color: Color(0xff9d9d9d),
                                            fontSize: AppFontSize.Size14),
                                      ),
                                      Text(
                                        list[index]['course_date'],
                                        style: TextStyle(
                                            color: Color(0xff494949),
                                            fontSize: AppFontSize.Size14),
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),

                    ));

                }),



          ),
        ),
      ],
    );
  }
}
